package com.sugon.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.sugon.dao.DevMainBaseDao;
import com.sugon.dao.MaintainPlanDao;
import com.sugon.entity.*;
import com.sugon.service.DevPlanGcRecordService;
import com.sugon.service.DevPlanGcService;
import com.sugon.service.MaintainPlanService;
import com.sugon.utils.ProcessInfoEnum;
import com.sugon.utils.ShiroUtils;
import com.sugon.utils.SysMsgType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 维护计划Service实现类
 *
 * @author sugon
 * @date 2019-08-07 14:02:42
 */
@Slf4j
@Service("maintainPlanService")
public class MaintainPlanServiceImpl implements MaintainPlanService {
    @Autowired
    private MaintainPlanDao maintainPlanDao;
    @Autowired
    private DevPlanGcService devPlanGcService;
    @Autowired
    private DevPlanGcRecordService devPlanGcRecordService;
    @Autowired
    private DevMainBaseDao devMainBaseDao;

    private ModuleMaintainPlanRelationEntity relationEntity;

    private SysMsgEntity msgEntity;

    private EquipmentRepairPersonEntity personEntity;

    @Override
    public MaintainPlanEntity queryObject(String id) {
        return maintainPlanDao.queryObject(id);
    }

    @Override
    public List<MaintainPlanEntity> queryList(Map<String, Object> map) {
        return maintainPlanDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return maintainPlanDao.queryTotal(map);
    }

    @Override
    public int save(MaintainPlanEntity maintainPlan) {
        String id = RandomUtil.randomString(32);
        maintainPlan.setId(id);
        String ruleId = maintainPlan.getRuleId();
        maintainPlan.setTypes(2);
        DevPlanGcEntity entity = new DevPlanGcEntity();
        entity.setDevGc(ruleId);
        entity.setDevPlan(id);
        //判断当前是否是周一,
        Date insDate = maintainPlan.getCarryDate();
        Date monday = getMonDay(insDate);
        entity.setStartTime(monday);
        entity.setEndTime(getEndDay(monday));
        //添加关联
        entity.setId(RandomUtil.randomString(32));
        entity.setCreateDate(new Date());
        entity.setCreateUser(ShiroUtils.getUserId());
        entity.setIsShow(0);
        entity.setStatus(0);
        entity.setUrge(0);
        devPlanGcService.save(entity);
        return maintainPlanDao.save(maintainPlan);
    }

    @Override
    public int saveApi(MaintainPlanEntity maintainPlan, String userId) {
        String id = RandomUtil.randomString(32);
        maintainPlan.setId(id);
        String ruleId = maintainPlan.getRuleId();
        maintainPlan.setTypes(2);
        DevPlanGcEntity entity = new DevPlanGcEntity();
        entity.setDevGc(ruleId);
        entity.setDevPlan(id);
        //判断当前是否是周一,
        Date insDate = maintainPlan.getCarryDate();
        Date monday = getMonDay(insDate);
        entity.setStartTime(monday);
        entity.setEndTime(getEndDay(monday));
        //添加关联
        entity.setId(RandomUtil.randomString(32));
        entity.setCreateDate(new Date());
        entity.setCreateUser(userId);
        entity.setIsShow(0);
        entity.setStatus(0);
        entity.setUrge(0);
        devPlanGcService.save(entity);
        return maintainPlanDao.save(maintainPlan);
    }

    @Override
    public int update(MaintainPlanEntity maintainPlan) {
        return maintainPlanDao.update(maintainPlan);
    }

    @Override
    public int delete(String id) {
        return maintainPlanDao.delete(id);
    }

    @Override
    public int deleteBatch(String[] ids) {
        return maintainPlanDao.deleteBatch(ids);
    }

    @Override
    public Integer insertMaintain(MaintainPlanEntity maintainPlanEntity, String devId) {
        HashMap<String, Object> hMap = new HashMap<>();
        List mmplrList = new ArrayList();
//        this.relationEntity = new ModuleMaintainPlanRelationEntity();
        /**
         * 维护计划id
         */
        String randomUUID = RandomUtil.randomString(32);
        maintainPlanEntity.setId(randomUUID);
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//            maintainPlanEntity.setCarryDate(dateFormat.format(new Date(maintainPlanEntity.getCarryDate())));
//            maintainPlanEntity.setCompleteDate(dateFormat.format(new Date(maintainPlanEntity.getCompleteDate())));
        Integer flag = maintainPlanDao.insertMaintain(maintainPlanEntity);
        if (flag > 0) {
            hMap.put("ID", devId);
            List<Map<String, Object>> devList = maintainPlanDao.selectModulMaintian(hMap);
            for (Map map : devList) {
                Map<String, Object> mapData = new HashMap<>();
                this.relationEntity = new ModuleMaintainPlanRelationEntity();
                /**
                 * 维护计划规程关联id
                 */
//                    mapData.put("id", RandomUtil.randomString(32));
                this.relationEntity.setId(RandomUtil.randomString(32));
                /**
                 * 维护选项id
                 */
//                    mapData.put("moId", map.get("MAINID"));
                this.relationEntity.setModuleOptionId(map.get("MAINID").toString());
                /**
                 * 维护计划id
                 */
//                    mapData.put("mpId", randomUUID);
                this.relationEntity.setModulePlanId(randomUUID);
                mmplrList.add(this.relationEntity);
            }
            Integer mainFla = maintainPlanDao.insertDevPlanOption(mmplrList);
            if (mainFla > 0) {
                SysMsgServiceImpl msgService = new SysMsgServiceImpl();
                this.msgEntity = new SysMsgEntity();
                this.msgEntity.setDataUrl("/sys/yearMaintainPlan.html");
                this.msgEntity.setDataType(ProcessInfoEnum.DEV_WHGD);
                this.msgEntity.setDataId(randomUUID);
                this.msgEntity.setDept(ShiroUtils.getDeptId());
                this.msgEntity.setType(SysMsgType.APPROVAL_REMIND);
                this.msgEntity.setTitle(ProcessInfoEnum.DEV_WHGC.getDesc());
                this.msgEntity.setUserId(ShiroUtils.getUserId());
                msgService.allMsgData(this.msgEntity);
            }
        }
        return flag;

    }

    @Override
    public List<Map<String, Object>> selectModulMaintian(String id) {
        HashMap<String, Object> modulMap = new HashMap<>();
        modulMap.put("ID", id);
        return maintainPlanDao.selectModulMaintian(modulMap);
    }

    @Override
    public Integer updatePlanReview(String id, String review) {
        return maintainPlanDao.updatePlanReview(id, review);
    }

    @Override
    public List<Map<String, Object>> queryDeptPerson() {
        try {
            List<Map<String, Object>> deptList = maintainPlanDao.selectSysUserDeptPerson(ShiroUtils.getDeptId());
            return deptList;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public Integer updatePlan(MaintainPlanEntity maintainPlanEntity, JSONArray personJSON) {
        List<EquipmentRepairPersonEntity> personList = new ArrayList<>();
        Integer perFlag = 0;
        try {
            Integer flag = maintainPlanDao.updateExecutive(maintainPlanEntity);
            if (flag > 0) {
                for (int i = 0; i < personJSON.size(); i++) {
                    this.personEntity = new EquipmentRepairPersonEntity();
                    this.personEntity.setId(RandomUtil.randomString(32));
                    this.personEntity.setRepairCode(maintainPlanEntity.getId());
                    this.personEntity.setPlanPerson(personJSON.get(i).toString());
                    personList.add(this.personEntity);
                }
                perFlag = maintainPlanDao.inAuxiliaryPlan(personList);
            }
            return perFlag;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public Integer delPlanPerson(JSONArray planId) {
        List ids = new ArrayList();
        for (int i = 0; i < planId.size(); i++) {
            ids.add(planId.get(i).toString());
        }
        return maintainPlanDao.delPlanPerson(ids);
    }

    @Override
    public List<Map<String, Object>> allDevPlan(String id) {
        return maintainPlanDao.allDevPlan(id);
    }

    @Override
    public Integer upStartDate(String id) {
        return maintainPlanDao.upStartDate(id);
    }

    @Override
    public Integer insertRecord(String rId, String pId, String carriedDate, String carriedName) {
        return maintainPlanDao.insertRecord(RandomUtil.randomString(32), rId, pId, carriedDate, carriedName);
    }

    @Override
    public Integer insertPlanChange(MaintainPlanChangeEntity changeEntity) {
        changeEntity.setId(RandomUtil.randomString(32));
        changeEntity.setChangePerson(ShiroUtils.getUserId());
        changeEntity.setChangeDate(currentDate());
        return maintainPlanDao.insertPlanChange(changeEntity);
    }

    /**
     * 时间方法
     *
     * @return
     */
    public String currentDate() {
        Date date = new Date();
        SimpleDateFormat dateType = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String dateFormat = dateType.format(date);
        return dateFormat;
    }

    @Override
    public Integer countPlanChange(String id) {
        return maintainPlanDao.countPlanChange(id);
    }

    @Override
    public List<MaintainPlanChangeEntity> reviewPlanChange() {
        return maintainPlanDao.reviewPlanChange();
    }

    @Override
    public Integer turnDownPlanChange(MaintainPlanChangeEntity changeEntity) {
        changeEntity.setApprovalPerson(ShiroUtils.getUserId());
        changeEntity.setApprovalDate(currentDate());
        changeEntity.setApprovalStatus("1");
        Integer flag = maintainPlanDao.turnDownPlanChange(changeEntity);
        if (flag > 0) {
            maintainPlanDao.delPlan(changeEntity.getMaintainPlanId());
            maintainPlanDao.delRecord(changeEntity.getMaintainPlanId());
            maintainPlanDao.delChange(changeEntity.getId(), changeEntity.getMaintainPlanId());
        }
        return flag;
    }

    @Override
    public Integer upExecutive(String id, String pid) {
        Integer flag = maintainPlanDao.upPlanExecutive(pid);
        Integer planFlag = 0;
        if (flag > 0) {
            planFlag = maintainPlanDao.delChange(id, pid);
        }
        return planFlag;
    }

    @Override
    public String endPlan(String id) {
        Integer countFlag = maintainPlanDao.countError(id);
        if (countFlag > 0) {
            return "异常状态暂未消除";
        }
        countFlag = maintainPlanDao.endPlan(id);
        if (countFlag > 0) {
            maintainPlanDao.upRecord(id);
        }
        return "计划已关闭";
    }

    /**
     * 自动执行生成维护计划数据
     *
     * @param maintainPlanEntity
     * @param devPlanList
     * @return
     */
    @Override
    public int autoSave(MaintainPlanEntity maintainPlanEntity, List<DevMaintenPlanEntity> devPlanList) {
        maintainPlanEntity.setId(RandomUtil.randomString(32));
        maintainPlanEntity.setCreateDate(new Date());
        return maintainPlanDao.save(maintainPlanEntity);
    }

    @Override
    public int apply(MaintainPlanEntity maintainPlanEntity) {
        maintainPlanEntity.setReview(ShiroUtils.getUserId());
        maintainPlanEntity.setAppTime(new Date());
        Integer status = maintainPlanEntity.getApprovalStatus();
        if (status == 1) {
            //审核通过   添加维护工单数据
            MaintainPlanEntity entity = queryObject(maintainPlanEntity.getId());
            //根据维护计划id查询维护规程id
            DevPlanGcEntity gc = devPlanGcService.queryObjectByPlanid(maintainPlanEntity.getId());

            Date end = entity.getCompleteDate();
            //判断当前时间是否大于结束时间
            if (new Date().before(end)) {
                //通过规程计划id 获取具体项
                List<DevMainBaseEntity> baseList = devMainBaseDao.getBaseInfo(entity.getId());
                for (DevMainBaseEntity base : baseList) {
                    DevPlanGcRecordEntity gcRecordEntity = new DevPlanGcRecordEntity();
                    gcRecordEntity.setBaseName(base.getName()); //选项名称
                    gcRecordEntity.setRelDevPlan(gc.getId());
                    gcRecordEntity.setBaseId(base.getId());//选项id
                    Integer rate = base.getFreRate();
                    gcRecordEntity.setFreRate(rate);//频率
                    //根据频率添加日期期限
                    Date start = gc.getStartTime();
                    Calendar curr = Calendar.getInstance();
                    curr.set(Calendar.HOUR_OF_DAY, 0);//控制时
                    curr.set(Calendar.MINUTE, 0);//控制分
                    curr.set(Calendar.SECOND, 0);//控制秒
                    curr.setTime(start);
                    gcRecordEntity.setStartTime(curr.getTime());
                    Date date = new Date();
                    if (rate == 1) {//每周,无法延期
                        Calendar curr1 = Calendar.getInstance();
                        curr1.set(Calendar.HOUR_OF_DAY, 0);//控制时
                        curr1.set(Calendar.MINUTE, 0);//控制分
                        curr1.set(Calendar.SECOND, 0);//控制秒
                        curr1.set(Calendar.DAY_OF_MONTH, curr1.get(Calendar.DAY_OF_MONTH) + 7);
                        gcRecordEntity.setDelayTime(curr1.getTime());
                    } else if (rate == 2) {//每两周
                        Calendar curr2 = Calendar.getInstance();
                        curr2.set(Calendar.HOUR_OF_DAY, 0);//控制时
                        curr2.set(Calendar.MINUTE, 0);//控制分
                        curr2.set(Calendar.SECOND, 0);//控制秒
                        curr2.set(Calendar.DAY_OF_MONTH, curr2.get(Calendar.DAY_OF_MONTH) + 14);
                        gcRecordEntity.setDelayTime(curr.getTime());
                    } else if (rate == 3) {//每月
                        Calendar curr3 = Calendar.getInstance();
                        curr3.set(Calendar.HOUR_OF_DAY, 0);//控制时
                        curr3.set(Calendar.MINUTE, 0);//控制分
                        curr3.set(Calendar.SECOND, 0);//控制秒
                        curr3.set(Calendar.MONTH, curr3.get(Calendar.MONTH) + 1);
                        gcRecordEntity.setDelayTime(curr3.getTime());
                    } else if (rate == 4) {//每个季度
                        Calendar curr4 = Calendar.getInstance();
                        curr4.set(Calendar.HOUR_OF_DAY, 0);//控制时
                        curr4.set(Calendar.MINUTE, 0);//控制分
                        curr4.set(Calendar.SECOND, 0);//控制秒
                        curr4.set(Calendar.MONTH, curr4.get(Calendar.MONTH) + 3);
                        gcRecordEntity.setDelayTime(curr4.getTime());
                    } else if (rate == 5) {//每半年
                        Calendar curr5 = Calendar.getInstance();
                        curr5.set(Calendar.HOUR_OF_DAY, 0);//控制时
                        curr5.set(Calendar.MINUTE, 0);//控制分
                        curr5.set(Calendar.SECOND, 0);//控制秒
                        curr5.set(Calendar.MONTH, curr5.get(Calendar.MONTH) + 6);

                        gcRecordEntity.setDelayTime(curr5.getTime());
                    } else if (rate == 6) {//一年
                        Calendar curr6 = Calendar.getInstance();
                        curr6.set(Calendar.HOUR_OF_DAY, 0);//控制时
                        curr6.set(Calendar.MINUTE, 0);//控制分
                        curr6.set(Calendar.SECOND, 0);//控制秒
                        curr.set(Calendar.YEAR, curr.get(Calendar.YEAR) + 1);
                        gcRecordEntity.setDelayTime(curr6.getTime());
                    }
                    gcRecordEntity.setEndTime(gc.getEndTime());
                    gcRecordEntity.setDelayTime(date);//最大延期时间
                    devPlanGcRecordService.save(gcRecordEntity);
                }
                devPlanGcService.showT(gc.getId());
            }
            //消息提醒
        }
        return maintainPlanDao.apply(maintainPlanEntity);
    }

    @Override
    public List<Map<String, Object>> getDetailsInfo(Map<String, Object> map) {
        return maintainPlanDao.getDetailsInfo(map);
    }

    @Override
    public int queryDetailsTotal(Map<String, Object> map) {
        return maintainPlanDao.queryDetailsTotal(map);
    }

    /**
     * 获取周一
     *
     * @return
     */
    private Date getMonDay(Date day) {
        Calendar c = Calendar.getInstance();
        c.setTime(day);
        int weekend = c.get(Calendar.DAY_OF_WEEK);
        if (weekend == 2) {
            return day;
        } else {
            c.setTime(getThisWeekMonday(day));
            c.add(Calendar.DATE, 7);
            return c.getTime();
        }


    }

    public Date getThisWeekMonday(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (2 == dayWeek) {
            cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 7);
            return cal.getTime();
        }
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一

        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        return cal.getTime();
    }

    public Date getEndDay(Date day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(day);
        cal.add(Calendar.WEEK_OF_MONTH, 1);
        return cal.getTime();
    }

    @Override
    public List<MaintainPlanEntity> getNotEndPlan() {
        return maintainPlanDao.getNotEndPlan();
    }

}
